import 'package:ease_call_kit/ease_call_kit.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:study_online/global/global.dart';
import 'package:study_online/pages/conversations/conversations_page.dart';

class ChatHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ChatHomePageState();
}

class _ChatHomePageState extends State<ChatHomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    _login();
    //_getheadImgUrl();
    // 初始化 EaseCallKit插件
    EaseCallKit.initWithConfig(
      EaseCallConfig('15cb0d28b87b425ea613fc46f7c9f974')
        ..userMap = {
          'du001': EaseCallUser('nick001', ''),
          'du002': EaseCallUser('nick002', ''),
        },
    );
    //_createDialog();
    _uploadHeadImg();
    _requestPermiss();
  }

  _login() async {
    await EMClient.getInstance.login('wind', "123456");
  }

  _createDialog() async {
    try {
      // emId: 会话对应环信id, 如果是群组或者聊天室，则为群组id或者聊天室id
      EMConversation conv =
          await EMClient.getInstance.chatManager.getConversation("chaser");
    } on EMError catch (e) {
      print('操作失败，原因是: $e');
    }
  }

  _uploadHeadImg() async {
    String headImg=Global.getInstance().user.photo;
    await EMClient.getInstance.userInfoManager.updateOwnUserInfoWithType(
        EMUserInfoType.EMUserInfoTypeAvatarURL,headImg);
  }

  @override
  Widget build(context) {
    super.build(context);
    _uploadHeadImg();
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(375, 667),
    );
    return Scaffold(
      body: ConversationPage(),
      // floatingActionButton: FloatingActionButton(
      //   child: Icon(Icons.add),
      //   onPressed: ()async{
      //     try {
      //       // emId: 会话对应环信id, 如果是群组或者聊天室，则为群组id或者聊天室id
      //       EMConversation conv = await EMClient.getInstance.chatManager.getConversation("test");
      //     } on EMError catch (e) {
      //       print('操作失败，原因是: $e');
      //     }
      //   },
      // ),
    );
  }

  /// 获取麦克风权限
  _requestPermiss() async {
    Future.delayed(Duration(seconds: 3)).then((value) {
      Permission.microphone.request();
    });
  }

  @override
  bool get wantKeepAlive => true;
}
